/*
 * @Date: 2021-12-09 19:48:46
 * @LastEditors: LeeKing
 * @LastEditTime: 2021-12-23 10:13:06
 * @FilePath: \hrsaas\src\store\modules\user.js
 */

import { login, getUserInfo, getUserInfoById } from '@/api/user.js'
import { setToken, getToken, removeToken, setTokenTime } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 给Token赋值
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  // 给UserInfo赋值
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 退出登录
  logout(state) {
    state.token = null
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  // 登录
  async login(context, payload) {
    const res = await login(payload)
    // 登录时间戳
    setTokenTime()
    context.commit('setToken', res)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getUserInfo()
    // 根据I的获取用户个人基本资料
    const userId = await getUserInfoById(res.userId)

    context.commit('setUserInfo', { ...res, ...userId })
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
